package com.baijiaoxi.common.model.base.model.extension;

import com.baijiaoxi.common.model.base.CommonError;
import com.baijiaoxi.common.model.base.CoreException;
import com.baijiaoxi.common.model.query.OrderColumn;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlInjectionUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public interface OrderByQuery {
    @JsonIgnore
    default void disableOrderBy() {

    }

    @JsonIgnore
    default boolean isDisableOrderBy() {
        return false;
    }

    @JsonIgnore
    default String getDefaultOrderBy() {
        return "";
    }

    default List<OrderColumn> getOrderList() {
        return null;
    }

    default void setOrderList(List<OrderColumn> orderList) {

    }

    default OrderByQuery addAsc(String asc) {
        if (getOrderList() == null)
            setOrderList(new ArrayList<>());
        this.getOrderList().add(OrderColumn.buildAsc(asc));
        return this;
    }

    default OrderByQuery addDesc(String desc) {
        if (getOrderList() == null)
            setOrderList(new ArrayList<>());
        this.getOrderList().add(OrderColumn.buildDesc(desc));
        return this;
    }

    @JsonIgnore
    default String getOrderByStr() {
        if (isDisableOrderBy())
            return "";
        String orderByStr = null;
        List<OrderColumn> orderList = this.getOrderList();
        if (orderList != null && !orderList.isEmpty()) {
            List<String> orderStrList = orderList.stream().filter(orderColumn ->
                            orderColumn.getOrderType() != null && !orderColumn.getOrderType().isEmpty() && !orderColumn.getOrderType().equalsIgnoreCase("normal")
                    ).map(orderColumn ->
                            String.format(" %s %s", orderColumn.getName(), orderColumn.getOrderType()))
                    .collect(Collectors.toList());
            orderByStr = String.join(",", orderStrList);
        }
        String resOrderStr = orderByStr == null || orderByStr.isEmpty() ? getDefaultOrderBy() : orderByStr;

        if (resOrderStr != null && !resOrderStr.isEmpty() && SqlInjectionUtils.check(resOrderStr))
            throw CoreException.create(CommonError.illegalOrderQuerySql, resOrderStr);
        else return resOrderStr;
    }

}